package com.zzy.chapter2.visitor;

import com.zzy.chapter2.pojo.AbstractProductItem;
import com.zzy.chapter2.pojo.ProductItemComposite;
import com.zzy.chapter2.utils.RedisCommonProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AddItemVisitor implements ItemVisitor<AbstractProductItem>{

    @Autowired
    private RedisCommonProcessor redisCommonProcessor;

    @Override
    public AbstractProductItem visit(AbstractProductItem productItem) {
        ProductItemComposite currentProductItem = (ProductItemComposite) redisCommonProcessor.get("productItem");
        ProductItemComposite addProductItem = (ProductItemComposite) productItem;
        if(currentProductItem.getId().equals(addProductItem.getPid())) {
            currentProductItem.addProductItem(addProductItem);
            return currentProductItem;
        }
        addChild(addProductItem, currentProductItem);
        return currentProductItem;
    }

    private void addChild(ProductItemComposite addProductItem, ProductItemComposite currentProductItem) {
        for (AbstractProductItem productItem : currentProductItem.getChild()) {
            ProductItemComposite currentItem = (ProductItemComposite) productItem;
            if(currentItem.getId().equals(addProductItem.getPid())) {
                currentItem.addProductItem(addProductItem);
                break;
            } else {
                addChild(addProductItem, currentItem);
            }
        }
    }
}
